/*START Related knowledge articles applet START*/
function getRelatedKBs() {
	var srch = pageForm.viewModel.Title + ' ' + pageForm.viewModel.Description;

	if(srch.length > 0) {
	//adds the related articles table to the task panel with an ID of kbTable
		$(".taskmenu").after("<div><h2>Related Articles</h2><table id=\"kbTable\"><tr><th></th></tr></table></div>");

		//list of common words, anything added to this list will be removed from the title
		var common = "i'm, with, the, many, able, it's, it, is, we, all, a, an, by, to, you, me, he, she, they, we, how, i, are, to, for, of, at, this, ok, so, if, while, and, also, too, because, since, as, also, such, but, though, yet, still, just, like";

		//this returns a clean array of uncommon words
		var searchArray = getUncommon(srch, common);
		var titleArray = getUncommon(pageForm.viewModel.Title, common);

		//convert array  of uncommon words to string for single search
		var searchString = [];
		for(var i=0;i < searchArray.length; i++) { 
			searchString += searchArray[i] + " ";
		};

		//make sure the title grab didnt fail or the title wasnt somehow empty
		if(searchString.length > 0) {
			//ajax call to the portal API
			$.ajax({
				url: "/api/V3/KnowledgeBase/GetHTMLArticlesFullTextSearch",
				async: true, //this is the default but showing that it can be turned off
				data: {
					userId: session.user.Id,
					searchValue: searchString,
					isManager: false
				},
				type: "GET", //this particular portal API call is a GET type
				success: function (data) { //this function is only run if the ajax call was successful, and it passes the array of returned items to the data
				    console.log('Found ' + data.length + ' related articles.');

				    //makes sure that the data array returned contains some results or it is ignored
				    if (data.length > 0) {
						//this section creates a new 'popular' object and then compares all of the objects in the array looking for the most popular article
					    var topArticle = data[0];

					    //Currently we just grab the first result as the most popular one since popularity is not automatically calculated
					    var mostRelevent = 0;
					    for (var i = 0; i < data.length; i++) {
					        var relevence = 0;
					        for (var j = 0; j < titleArray.length; j++) {
					            var occured = occurrences(data[i].Title, titleArray[j])
					            relevence += occured;
					        }

					        //Checks to see if this article has more relevent words in the title than the last
                            //Also, sets the current most relevent count
					        if (relevence > mostRelevent) {
					            topArticle = data[i];
					            mostRelevent = relevence;
					        }
					    }

						/*	adds a hidden element to the top of the form that contains the article data for the most popular article
							it then adds the required CSS (this CSS could also be placed in the custom.css file)
							it then slides the alert down from the top all stylish! */
						$(".page_bar").after("<div class=\"kbNotification col-md-12\" style=\"display: none\"><a href=\"/KnowledgeBase/View/" + topArticle.ArticleId + "\">" + "KB" + topArticle.ArticleId + ": " + topArticle.Title + "</a></div>");
						$(".kbNotification").css({
												'position': 'absolute',
												'z-index': 1,
												'top': 59,
												'line-height': 2.5,
												'overflow': 'hidden',
												'box-shadow': '0 5px 5px -5px #333',
												'background-color': 'orange',
												'color': 'white',
												'text-align': 'center',
												'padding': '0px'
											}).slideDown();
						$(".kbNotification a").css({
												'color': 'white',
												'font-size': '14px'
												});
						//this runs through the data array and adds the first 5 returned results to the Related KBs table
						for (var i = 0; i < data.length && i < 5; i++) {
							$("#kbTable > tbody > tr")
								.last()
								.after("<tr><td nowrap><a href=\"/KnowledgeBase/View/" + data[i].ArticleId + "\">" + data[i].Title.substring(0,20) + "..." + "</a></td></tr>");
							$("#kbTable > tbody > tr > td").css({
																'padding': '3px',
																'font-size': '14px'
															});
						}
					}
				}
			});		
		};

		//This function cleans up the search string by comparing it against a list of common words and then return an array with uncommon words
		function getUncommon(sentence, common) {
		    var commonArray = common.split(',');
		    for (var i = 0; i < commonArray.length; i++) {
		        commonArray[i] = commonArray[i].trim();
		        commonArray[i] = commonArray[i].toLowerCase();
		    };

		    var sentenceArray = sentence.split(' ');
		    for (var i = 0; i < sentenceArray.length; i++) {
		        sentenceArray[i] = sentenceArray[i].replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g, "")
		        sentenceArray[i] = sentenceArray[i].trim();
		        sentenceArray[i] = sentenceArray[i].toLowerCase();
		    };

		    //searches through each word in the search array and matches to common words
		    //builds a new array that doesn't have the common words in it
		    var uncommonArray = [];
		    for (var i = 0; i < sentenceArray.length; i++) {
		        var found = false;
                //this can be faster if you use a while statement and quit on first true
		        for (var j = 0; j < commonArray.length; j++) {
		            if (sentenceArray[i] == commonArray[j]) {
		                found = true;
		            };
		        };

		        if (found == false) {
		            uncommonArray.push(sentenceArray[i]);
		        };
		    }

		    return uncommonArray;
		};

	    /*
            Function count the occurrences of substring in a string;
            @param {String} string   Required. The string;
            @param {String} subString    Required. The string to search for;
            @param {Boolean} allowOverlapping    Optional. Default: false;
        */
		function occurrences(string, subString, allowOverlapping) {

		    string += ""; subString += "";
		    if (subString.length <= 0) return string.length + 1;

		    var n = 0, pos = 0;
		    var step = (allowOverlapping) ? (1) : (subString.length);

		    while (true) {
		        pos = string.indexOf(subString, pos);
		        if (pos >= 0) { n++; pos += step; } else break;
		    }
		    return (n);
		};

	} else {
		console.log('Related KB Ext: Search string empty');
	};
}
/*END Related knowledge articles applet END*/